package com.my.socket.bio.v2;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;

/**
 * Created by ZhongGang
 * at 2018/6/27 10:07
 */
public class ReverseClient {
    private static final Logger LOGGER = LoggerFactory.getLogger(ReverseClient.class);

    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        Semaphore semaphore = new Semaphore(50);
        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try (Socket socket = new Socket()) {
                        semaphore.acquire();
                        socket.connect(new InetSocketAddress("127.0.0.1", 9999));
                        OutputStream outputStream = socket.getOutputStream();
                        PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream));
                        writer.println("GET HTTP/1.0");
                        writer.flush();

                        InputStream inputStream = socket.getInputStream();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                        String line = reader.readLine();
                        LOGGER.info("received reversed line {}", line);
                    } catch (Exception e) {
                        LOGGER.error("exception caught, the error is {}", e.getMessage());
                    } finally {
                        semaphore.release();
                    }
                }
            });
            threads.add(thread);
            thread.start();
        }

        for (Thread thread : threads) {
            thread.join();
        }

        LOGGER.info("it takes {} second(s)", (System.currentTimeMillis() - start) / 1000.00);
    }
}
